package com.quasar.hpatient.view.personal.setup;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.android.gms.plus.model.people.Person;
import com.hyphenate.EMCallBack;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.event.CloseEvent;
import com.quasar.hpatient.model.httpmodel.OuterLayerDataResult;
import com.quasar.hpatient.model.litePalmodel.TestCachedb;
import com.quasar.hpatient.model.medicalmodel.UpdateEdition;
import com.quasar.hpatient.model.operationmodel.AccountInfo;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.step.bean.StepData;
import com.quasar.hpatient.utils.LogAndToastUtil;
import com.quasar.hpatient.utils.SystemTool;
import com.quasar.hpatient.view.LoginActivity_;
import com.quasar.hpatient.widget.EaseSwitchButton;
import com.quasar.hpatient.widget.MyViews;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;

import chatui.DemoHelper;
import chatui.DemoModel;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.quasar.hpatient.step.utils.DbUtils.liteOrm;

/**
 * author : 许建宏
 * Date: 2017/10/7 0026
 * View:设置
 */
@EActivity(R.layout.activity_setting)
public class SettingActivity extends BaseActivity {

    private static final String TAG = "SettingActivity";
    //保存版本信息
    UpdateEdition updata;
    private DemoModel settingsModel;

    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    //新消息提醒
    @ViewById(R.id.eb_new_mess)
    EaseSwitchButton eb_new_mess;
    //版本更新
    @ViewById(R.id.mv_edition)
    MyViews mv_edition;
    //声音提醒
    @ViewById(R.id.eb_st_voice)
    EaseSwitchButton eb_st_voice;
    //震动提醒
    @ViewById(R.id.eb_st_shock)
    EaseSwitchButton eb_st_shock;
    @ViewById(R.id.rl_shengYin)
    RelativeLayout rl_shengYin;
    @ViewById(R.id.rl_zhenDong)
    RelativeLayout rl_zhenDong;
    //消息免打扰
    @ViewById(R.id.eb_st_disturb)
    EaseSwitchButton eb_st_disturb;
    //关闭药单提醒
    @ViewById(R.id.eb_close_prescription)
    EaseSwitchButton eb_close_prescription;


    @AfterViews
    void init() {
        ViseLog.d("enter");

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        settingsModel = DemoHelper.getInstance().getModel();


        if (settingsModel.getSettingMsgNotification()) {
            eb_st_disturb.openSwitch();
            rl_shengYin.setVisibility(View.VISIBLE);
            rl_zhenDong.setVisibility(View.VISIBLE);
            settingsModel.setSettingMsgNotification(true);
        } else {
            eb_st_disturb.closeSwitch();
            rl_shengYin.setVisibility(View.GONE);
            rl_zhenDong.setVisibility(View.GONE);
            settingsModel.setSettingMsgNotification(false);
        }


        if (settingsModel.getSettingMsgSound()) {
            eb_st_voice.openSwitch();
        } else {
            eb_st_voice.closeSwitch();
        }

        //震动

        if (settingsModel.getSettingMsgVibrate()) {
            eb_st_shock.openSwitch();
        } else {
            eb_st_shock.closeSwitch();
        }

        initView();
        PostEdition();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CloseEvent closeEvent) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //新消息提醒
    @Click(R.id.eb_new_mess)
    public void eb_new_mess() {
        if (eb_new_mess.isSwitchOpen()) {
            eb_new_mess.closeSwitch();
        } else {
            eb_new_mess.openSwitch();
        }
    }

    //版本更新
    @Click(R.id.mv_edition)
    public void mv_edition() {
        if (updata != null) {
            UpAppActivity_.intent(this).updateEdition(updata).start();
        } else {
            LogAndToastUtil.toast(this, "已经是最新版本", "");
        }
    }

    //声音提醒
    @Click(R.id.eb_st_voice)
    public void eb_st_voice() {
        if (eb_st_voice.isSwitchOpen()) {
            eb_st_voice.closeSwitch();
            settingsModel.setSettingMsgSound(false);
        } else {
            eb_st_voice.openSwitch();
            settingsModel.setSettingMsgSound(true);
        }
    }

    //震动提醒
    @Click(R.id.eb_st_shock)
    public void eb_st_shock() {
        if (eb_st_shock.isSwitchOpen()) {
            eb_st_shock.closeSwitch();
            settingsModel.setSettingMsgVibrate(false);
        } else {
            eb_st_shock.openSwitch();
            settingsModel.setSettingMsgVibrate(true);
        }
    }

    //消息免打扰
    @Click(R.id.eb_st_disturb)
    public void eb_st_disturb() {

        if (eb_st_disturb.isSwitchOpen()) {
            eb_st_disturb.closeSwitch();
            rl_shengYin.setVisibility(View.GONE);
            rl_zhenDong.setVisibility(View.GONE);
            settingsModel.setSettingMsgNotification(false);
        } else {
            eb_st_disturb.openSwitch();
            rl_shengYin.setVisibility(View.VISIBLE);
            rl_zhenDong.setVisibility(View.VISIBLE);
            settingsModel.setSettingMsgNotification(true);
        }
    }

    //意见反馈
    @Click(R.id.mv_feedback)
    public void mv_feedback() {
        FeedbackActivity_.intent(this).start();
    }

    //使用帮助
    @Click(R.id.mv_help)
    public void mv_help() {
        UsehelpActivity_.intent(this).start();
    }

    //关闭药单提醒
    @Click(R.id.eb_close_prescription)
    public void eb_close_prescription() {

        if (eb_close_prescription.isSwitchOpen()) {
            eb_close_prescription.closeSwitch();
        } else {
            eb_close_prescription.openSwitch();
        }
    }

    //更改密码
    @Click(R.id.my_pwd)
    public void my_pwd() {
        UpdatePwdActivity_.intent(this).start();
    }

    @Click(R.id.mv_phone)
    public void mv_phone() {
        UpdatePhoneActivity_.intent(this).start();
    }

    //注销
    @Click(R.id.bt_login)
    public void bt_login() {
        showDialog();
        AccountInfo.loginOut(this);
        EventBus.getDefault().post(new CloseEvent());

        DemoHelper.getInstance().logout(false, new EMCallBack() {
            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        pd.dismiss();
                        // 3. 删除全部
                        liteOrm.deleteAll(StepData.class);
                        //退出时删除化验单信息
                        try {
                            DataSupport.deleteAll(TestCachedb.class);
                        }catch (Exception e){
                            ViseLog.d("删除化验单数据"+e.getMessage());
                        }

                        finish();
                        //注销密码
//                        MainAppliaction.getInstance().setPwd("");
                        startActivity(new Intent(SettingActivity.this, LoginActivity_.class));
                    }
                });
            }
            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        pd.dismiss();
                        Toast.makeText(SettingActivity.this, "unbind devicetokens failed", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    //检测版本请求
    public void PostEdition() {
        ViseLog.d("enter");
        RetrofitConnection.getBasicDataUrls().UpApp(ConstantManger.userType)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OuterLayerDataResult<UpdateEdition>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull OuterLayerDataResult<UpdateEdition> updateEditionOuterLayerDataResult) {

                        ViseLog.d("onNext" + updateEditionOuterLayerDataResult);
                        if(updateEditionOuterLayerDataResult.getData()!=null){
                            if (updateEditionOuterLayerDataResult.getData().getVersion() != null &&
                                    updateEditionOuterLayerDataResult.getData().getVersion().length() > 0) {
                                //网络最新的apk版本信息
                                int PostVersion = Integer.parseInt(updateEditionOuterLayerDataResult.getData().getVersion());
                                //当前apk的版本号
                                int version = SystemTool.getAppVersionCode(SettingActivity.this);

                                if (PostVersion > version) {
                                    mv_edition.setNum(1);
                                    updata = updateEditionOuterLayerDataResult.getData();
                                } else {
                                    mv_edition.setNum(-1);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                        ViseLog.d(TAG, "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        ViseLog.d(TAG, "onComplete: ");
                    }
                });
    }

    @Override
    protected void initView() {
        initToolbar();
    }

    @Override
    protected void initData() {

    }
}
